<template>
  <div>
    <!-- 筛选、搜索 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <!-- <el-form-item label="模糊搜索">
            <el-input
              v-model="formInline.query_str"
              placeholder="请输入"
              clearable
            />
          </el-form-item> -->
      <el-form-item label="专家组">
        <el-select
          v-model="formInline.project_group"
          placeholder="专家组"
          @change="handleGroupChange"
        >
          <el-option
            v-for="item in projectGroups"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="批次">
        <el-select v-model="formInline.batch_name" placeholder="批次">
          <el-option
            v-for="item in batches"
            :label="item.batch_name"
            :value="item.batch_name"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleCurrentChange(1)"
          >查询</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="exportFile">导出</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div v-if="tableData.length > 0">
    <el-table
      ref="multipleTableRef"
      v-loading="tabLoading"
      :data="tableData"
      border
      style="width: 100%"
      height="500"
      :row-style="{ height: '60px' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        :label="key"
        v-for="key in columns"
        :fixed="isFixed(key)"
        show-overflow-tooltip="true"
      >
        <template #default="scope">
          {{ scope.row[key] }}
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click.prevent="handleDetail(scope.row)"
            >评审</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block items-center justify-center">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="cnt"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <div v-if="tableData.length == 0">
    <el-empty description="无记录" />
  </div>

  <form-drawer
    ref="formDrawerRef"
    title="项目详情"
    destroyOnClose
    :showButton="false"
  >
    <el-descriptions
      title="项目基础信息"
      direction="vertical"
      :column="4"
      :size="size"
      border
    >
      <el-descriptions-item label="项目编码">{{
        detailProject.value.project_code
      }}</el-descriptions-item>
      <el-descriptions-item label="项目名称">{{
        detailProject.value.project_name
      }}</el-descriptions-item>
      <el-descriptions-item label="项目类别">{{
        detailProject.value.project_class
      }}</el-descriptions-item>
      <el-descriptions-item label="项目规模">
        {{ detailProject.value.project_type }}
      </el-descriptions-item>
      <el-descriptions-item label="项目专家组"
        >{{ detailProject.value.project_group }}
      </el-descriptions-item>
      <el-descriptions-item label="项目提交时间"
        >{{ formatDate(detailProject.value.createTime) }}
      </el-descriptions-item>
      <el-descriptions-item label="项目所在批次"
        >{{
          detailProject.value.project_batch == null
            ? detailProject.value.project_batch
            : detailProject.value.project_batch.batch_name
        }}
      </el-descriptions-item>
      <el-descriptions-item label="项目状态"
        >{{ detailProject.value.statu }}
      </el-descriptions-item>
    </el-descriptions>

    <el-descriptions
      :title="'项目成员' + (index + 1)"
      :column="4"
      :size="size"
      direction="vertical"
      :style="blockMargin"
      border
      v-for="(item, index) in detailProject.value.project_member"
      class="mt-2"
    >
      <el-descriptions-item label="成员名">{{
        item.user_fullname
      }}</el-descriptions-item>
      <el-descriptions-item label="成员所在部门">{{
        item.user_department
      }}</el-descriptions-item>
      <el-descriptions-item label="成员贡献占比" :span="2">{{
        item.menbers_percentage
      }}</el-descriptions-item>
      <el-descriptions-item label="成员主要负责项目内容">
        {{ item.members_job }}
      </el-descriptions-item>
    </el-descriptions>

    <el-descriptions
      title="项目文件"
      :column="4"
      :size="size"
      direction="vertical"
      :style="blockMargin"
      border
      class="mt-2"
    >
      <el-descriptions-item label="文件列表(点击下载)">
        <el-link
          class="ml-5"
          type="success"
          v-for="item in detailProject.value.project_file"
          v-if="detailProject.value.project_file.length > 0"
          :href="'/api/v1/download_file/' + item.id"
          @click="handleFileTag(item.id)"
          >{{ item.file_path }}</el-link
        >
        <span v-else>无</span>
      </el-descriptions-item>
    </el-descriptions>

    <el-descriptions
      title="项目描述"
      :column="4"
      :size="size"
      direction="vertical"
      :style="blockMargin"
      class="mt-2"
      border
    >
      <el-descriptions-item>
        <el-collapse v-model="activeName" accordion>
          <el-collapse-item title="项目简介" name="1">
            <div>
              {{ detailProject.value.project_brief }}
            </div>
          </el-collapse-item>
          <el-collapse-item title="项目背景" name="2">
            <div>
              {{ detailProject.value.project_background }}
            </div>
          </el-collapse-item>
          <el-collapse-item title="项目创新点" name="3">
            <div>
              {{ detailProject.value.project_annotation }}
            </div>
          </el-collapse-item>
          <el-collapse-item title="项目应用/推广价值" name="4">
            <div>
              {{ detailProject.value.project_effect }}
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-descriptions-item>
    </el-descriptions>

    <el-descriptions
      title="项目操作记录"
      :column="4"
      :size="size"
      direction="vertical"
      :style="blockMargin"
      border
      class="mt-2"
    >
      <el-descriptions-item label="记录">
        <el-timeline class="mt-2">
          <el-timeline-item
            v-for="(item, index) in detailProject.value.project_log"
            :key="index"
            type="primary"
            size="large"
            hollow="true"
            :timestamp="formatDate(item.createTime)"
          >
            {{ item.statu }}
          </el-timeline-item>
        </el-timeline>
      </el-descriptions-item>
    </el-descriptions>

    <el-descriptions
      title="打分"
      :column="pointsCols"
      :size="size"
      direction="vertical"
      :style="blockMargin"
      border
      class="mt-2"
    >
      <el-descriptions-item :label="key" v-for="(value, key) in pointsData">
        {{ value }}
      </el-descriptions-item>
    </el-descriptions>

    <el-button class="flex bottom-3 fixed" type="primary" size="small" @click.prevent="handleAudit"
      >评审</el-button
    >
  </form-drawer>

  <el-dialog v-model="dialogFormVisible" title="评审结果" draggable>
    <el-form :model="batchForm">
      <el-form-item label="所属专家组" label-width="140px">
        <el-input v-model="formInline.project_group" disabled />
      </el-form-item>
      <el-form-item label="批次名称" label-width="140px">
        <el-input v-model="formInline.batch_name" disabled />
      </el-form-item>
      <el-form-item label="项目编号" label-width="140px">
        <el-input v-model="detailProject.value.project_code" disabled />
      </el-form-item>
      <el-form-item label="项目名称" label-width="140px">
        <el-input v-model="detailProject.value.project_name" disabled />
      </el-form-item>
      <el-form-item label="评审结果" label-width="140px">
        <el-radio-group v-model="auditRes" class="ml-4">
          <el-radio label="true" size="large">通过</el-radio>
          <el-radio label="false" size="large">不通过</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, onUpdated, reactive, ref } from "vue";
import { ElLoading } from "element-plus";
import {
  getProjectsByUser,
  getUserGroups,
  download_file,
  getTaggingProjects,
  tag_batch,
  getBatches,
  getProjectsByGroup,
  getAuditRule,
  audit,
  getAuditedProject,
  getBatchProjectsWithAuditInfo,
  getProjectByProjectCode,
  submitProjectAuditRes,
} from "@/api/apiv1";
import { formatDate, message } from "@/composables/util";

import FormDrawer from "@/components/FormDrawer.vue";

const dialogFormVisible = ref(false);
const batches = ref([]);
const tabLoading = ref(false);
const tableData = ref([]);
const cnt = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const formDrawerRef = ref(null);
const detailProject = reactive({});

const projectGroups = ref([]);

const projectLogs = ref([]);

const columns = ref([]);

const auditRes = ref([]);

const isFixed = (colName) => {
  if (colName == "专家组评审项目得分" || colName == "是否通过") {
    return "right";
  } else {
    return false;
  }
};

const formInline = reactive({
  project_group: "",
  batch_name: "",
});

const pointsCols = ref(0);
const pointsData = reactive({});

const pointsForm = ref([
  {
    point: 0,
  },
]);

const generateColumns = (records) => {
  columns.value = [];
  let item = records[0];
  for (let key in item) {
    columns.value.push(key);
  }
};

const auditRules = ref([]);

const multipleSelection = ref([]);

const handleSelectionChange = (v) => {
  multipleSelection.value = v;
};

const tableDateFormatter = (row, column) => {
  return formatDate(row.createTime);
};

const init = () => {
  getUserGroups().then((res) => {
    projectGroups.value = res.data;
    formInline.project_group = projectGroups.value[0];
    initBatches(formInline.project_group);
  });
};

const initBatches = (project_group) => {
  getBatches(project_group).then((res) => {
    batches.value = res.data.records;
    formInline.batch_name = batches.value[0].batch_name;
  });
};

const getData = () => {
  tabLoading.value = true;
  getBatchProjectsWithAuditInfo(
    formInline.project_group,
    formInline.batch_name,
    false,
    pageSize.value,
    currentPage.value
  ).then((res) => {
    if (res.code == 200) {
      cnt.value = res.data.cnt;
      tableData.value = res.data.records;
      generateColumns(tableData.value);
      console.log(columns.value);
    } else {
      message(res.msg, "error");
    }

    tabLoading.value = false;

    console.log(tableData.value);
  });
};

const exportFile = () => {
  getBatchProjectsWithAuditInfo(
    formInline.project_group,
    formInline.batch_name,
    true,
    pageSize.value,
    currentPage.value
  ).then((res) => {
    let fileName = formInline.batch_name + "评审结果.xlsx";
    // 将二进制流转为blob
    const blob = new Blob([res]);
    if (typeof window.navigator.msSaveBlob !== "undefined") {
      // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
      window.navigator.msSaveBlob(blob, decodeURI(fileName));
    } else {
      // 创建新的URL并指向File对象或者Blob对象的地址
      const blobURL = window.URL.createObjectURL(blob);
      // 创建a标签，用于跳转至下载链接
      const tempLink = document.createElement("a");
      tempLink.style.display = "none";
      tempLink.href = blobURL;
      tempLink.setAttribute("download", decodeURI(fileName));
      // 兼容：某些浏览器不支持HTML5的download属性
      if (typeof tempLink.download === "undefined") {
        tempLink.setAttribute("target", "_blank");
      }
      // 挂载a标签
      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL);
    }
  });
};

onMounted(() => {
  init();
});

const handleGroupChange = (v) => {
  initBatches(v);
};

const handleSizeChange = (v) => {
  pageSize.value = v;
  getData();
};
const handleCurrentChange = (v) => {
  currentPage.value = v;
  getData();
};

const confirmAudit = () => {
  audit(detailProject.value.id, pointsForm.value).then((res) => {
    if (res.code == 200) {
      message("提交成功");
      formDrawerRef.value.close();
      getData();
    } else {
      message(res.msg, "error");
    }
  });
};

const handleDetail = (row) => {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  //   detailProject.value = tableData.value[index];
  //   console.log(detailProject.value);
  //   formDrawerRef.value.open();
  getProjectByProjectCode(row["项目编码"]).then((res) => {
    if (res.code == 200) {
      detailProject.value = res.data;
      console.log(detailProject.value);

      //   pointsData.value = [] // 清空 pointsData
      Object.assign(pointsData, {}); // 清空 pointsData
      let tempData = {};
      for (let index in detailProject.value.audit_records) {
        let item = detailProject.value.audit_records[index];
        console.log(item);
        if (!(item.user.username in tempData)) {
          tempData[item.user.username] = { 评委: item.user.fullname };
        }
        tempData[item.user.username][item.dimension] = item.point;
      }

      if (detailProject.value.audit_records.length > 0){
        pointsCols.value =
        Object.keys(
          tempData[detailProject.value.audit_records[0].user.username]
        ).length + 1;
      } else {
        pointsCols.value = 0
      }
    
      console.log(pointsCols.value);
      let j = 1;
      for (let username in tempData) {
        let items = tempData[username];
        let total = 0;
        for (let item in items) {
          pointsData[item + j] = items[item];
          if (item != "评委") {
            total += items[item];
          }
        }
        pointsData["总分" + j] = total;
        j += 1;
      }

      console.log(pointsData);
      formDrawerRef.value.open();
    } else {
      message(res.msg, "error");
    }
    loading.close();
  });
};

const handleAudit = (row) => {
  dialogFormVisible.value = true;
};

const submitAudit = () => {
  console.log(detailProject.value)
  console.log(auditRes.value)
  submitProjectAuditRes(detailProject.value.id,detailProject.value.project_group,auditRes.value).then(res => {
    if (res.code == 200){
      message(res.msg);
      dialogFormVisible.value = false;
      formDrawerRef.value.close();
      getData();
    }else{
      message(res.msg,"error");
    }
  })
};

</script>

<style scoped>
/* .slider-demo-block {
    display: flex;
    align-items: center;
  }
  .slider-demo-block .el-slider {
    margin-top: 0;
    margin-left: 2px;
  }
  .slider-demo-block .demonstration {
    font-size: 14px;
    color: var(--el-text-color-secondary);
    line-height: 44px;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-bottom: 0;
  }
  .slider-demo-block .demonstration + .el-slider {
    flex: 0 0 80%;
  } */
</style>
